#include "stdafx.h"
#include "Log.h"


CLog::CLog()
{
	m_nRef = 0;
	m_nMessageLen = 0;
	m_szMessage[m_nMessageLen] = '\0';
	m_fReleaseListener = nullptr;
	m_pFrom = NULL;
	::InitializeCriticalSection(&m_cs);
}

CLog::CLog(const CLog & scr)
{
	m_nRef = 0;
	::InitializeCriticalSection(&m_cs);
	m_time = scr.m_time;
	m_pFrom = scr.m_pFrom;
	m_nLevel = scr.m_nLevel;
	m_nMessageLen = scr.m_nMessageLen;
	memcpy(m_szMessage, scr.m_szMessage, m_nMessageLen);
	m_szMessage[m_nMessageLen] = '\0';
	m_fReleaseListener = nullptr;
}

int CLog::setLog(void *pFrom, int nLevel, char *pszText)
{
	lock();
	time(&m_time);
	m_pFrom = pFrom;
	m_nLevel = nLevel;
	m_nMessageLen = min(1023, (int)strlen(pszText));
	memcpy(m_szMessage, pszText, m_nMessageLen);
	m_szMessage[m_nMessageLen] = '\0';
	unlock();

	return m_nMessageLen;
}

CLog::~CLog()
{
	::DeleteCriticalSection(&m_cs);
}

void CLog::SetReleaseListener(RELEASELISTENER listener)
{
	m_fReleaseListener = listener;
}
int CLog::AddRef()
{
	lock();
	m_nRef++;
	unlock();

	return m_nRef;
}

int CLog::Release()
{
	lock();
	if (m_nRef > 0) {
		m_nRef--;

		if (m_nRef == 0 && m_fReleaseListener != nullptr) {
			m_fReleaseListener(this);
		}
	}
	unlock();

	return m_nRef;
}

inline void CLog::lock()
{
	::EnterCriticalSection(&m_cs);
}

inline void CLog::unlock()
{
	::LeaveCriticalSection(&m_cs);
}